package com.abc.recycling.controller;

import com.abc.recycling.domain.SysLog;
import com.abc.recycling.service.SysLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Controller
@RequestMapping("/log")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class SysLogController {

    private final SysLogService logService;
    
    /**
     * 日志列表页面
     */
    @GetMapping("/list")
    public String list(Model model) {
        return "log/list";
    }
    
    /**
     * 日志详情页面
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Long id, Model model) {
        SysLog log = logService.getLog(id);
        model.addAttribute("log", log);
        return "log/detail";
    }
    
    /**
     * 搜索日志
     */
    @GetMapping("/search")
    @ResponseBody
    public List<SysLog> search(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        return logService.searchLogs(title, type, username, status, startTime, endTime);
    }
    
    /**
     * 清空日志
     */
    @DeleteMapping("/clean")
    @ResponseBody
    public int clean(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime time) {
        return logService.cleanLogsBefore(time);
    }
    
    /**
     * 批量删除日志
     */
    @DeleteMapping("/batch")
    @ResponseBody
    public int batchDelete(@RequestBody List<Long> ids) {
        return logService.deleteLogs(ids);
    }
    
    /**
     * 统计日志数量
     */
    @GetMapping("/count")
    @ResponseBody
    public int count(
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        return logService.countLogs(type, status, startTime, endTime);
    }
} 